﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace YB_Server_Windows
{
    public static class PopupWindow
    {
        private static List<PopWindow> WindowList = new List<PopWindow>();
        private static int formWidth = 300;
        private static int formHeight = 120;
        private static int formMargin = 10;
        public static int Count { get { return WindowList.Count; } }
        public static PopWindow AddNewWindow(string title, string content, System.Drawing.Image icon = null)
        {
            return new PopWindow(title, content, icon);
        }


        private static void ArrangeWindows()
        {
            int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
            int left = screenWidth - formWidth - formMargin;
            int top = screenHeight - formHeight - formMargin;

            for (int i = WindowList.Count - 1; i >= 0; i--)
            {
                WindowList[i].form.Location = new Point(left, top);
                top -= (formHeight + formMargin);

                if (top < formMargin)
                {
                    top = screenHeight - formHeight - formMargin;
                    left -= (formWidth + formMargin);
                }
            }
        }
        public static Bitmap AdjustHue(Bitmap image, float hue)
        {
            // 创建一个颜色矩阵对象
            ColorMatrix colorMatrix = new ColorMatrix();

            // 计算绕基色轴旋转的弧度
            float hueRadians = hue / 180.0f * (float)Math.PI;

            // 计算三原色分量旋转的变换矩阵
            float cos = (float)Math.Cos(hueRadians);
            float sin = (float)Math.Sin(hueRadians);

            // 红色到绿色的旋转矩阵
            colorMatrix[0, 0] = cos + (1.0f - cos) / 3.0f;
            colorMatrix[0, 1] = 1.0f / 3.0f * (1.0f - cos) - (float)Math.Sqrt(1.0f / 3.0f) * sin;
            colorMatrix[0, 2] = 1.0f / 3.0f * (1.0f - cos) + (float)Math.Sqrt(1.0f / 3.0f) * sin;

            // 绿色到蓝色的旋转矩阵
            colorMatrix[1, 0] = 1.0f / 3.0f * (1.0f - cos) + (float)Math.Sqrt(1.0f / 3.0f) * sin;
            colorMatrix[1, 1] = cos + 1.0f / 3.0f * (1.0f - cos);
            colorMatrix[1, 2] = 1.0f / 3.0f * (1.0f - cos) - (float)Math.Sqrt(1.0f / 3.0f) * sin;

            // 蓝色到红色的旋转矩阵
            colorMatrix[2, 0] = 1.0f / 3.0f * (1.0f - cos) - (float)Math.Sqrt(1.0f / 3.0f) * sin;
            colorMatrix[2, 1] = 1.0f / 3.0f * (1.0f - cos) + (float)Math.Sqrt(1.0f / 3.0f) * sin;
            colorMatrix[2, 2] = cos + 1.0f / 3.0f * (1.0f - cos);

            // 创建一个图像属性对象，并设置颜色矩阵
            ImageAttributes attributes = new ImageAttributes();
            attributes.SetColorMatrix(colorMatrix);

            // 创建一个目标图像对象，并应用颜色矩阵
            Bitmap result = new Bitmap(image.Width, image.Height);
            using (Graphics graphics = Graphics.FromImage(result))
            {
                graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
                    0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
            }

            return result;
        }
        private static void CalculateGradientPoints(Rectangle rectangle, float gradientAngle, ref Point startPoint, ref Point endPoint)
        { // 将角度转换为弧度
            double radians = gradientAngle * Math.PI / 180;

            // 计算圆角四边形对角线的长度
            double diagonalLength = Math.Sqrt(rectangle.Width * rectangle.Width + rectangle.Height * rectangle.Height);

            // 计算起点和终点的偏移量
            double startXOffset = (diagonalLength / 2) * Math.Cos(radians + Math.PI);
            double startYOffset = (diagonalLength / 2) * Math.Sin(radians + Math.PI);
            double endXOffset = (diagonalLength / 2) * Math.Cos(radians);
            double endYOffset = (diagonalLength / 2) * Math.Sin(radians);

            // 计算起点和终点的坐标
            startPoint = new Point(rectangle.Left + rectangle.Width / 2 + (int)startXOffset, rectangle.Top + rectangle.Height / 2 + (int)startYOffset);
            endPoint = new Point(rectangle.Left + rectangle.Width / 2 + (int)endXOffset, rectangle.Top + rectangle.Height / 2 + (int)endYOffset);
        }
        public static void DrawGradientRoundedRectangle(Graphics graphics, Pen pen, Color startColor, Color endColor, Rectangle rectangle, int cornerRadius, float gradientAngle, bool needpath = false)
        {
            try
            {
                int diameter = cornerRadius * 2;
                Size size = new Size(diameter, diameter);
                Rectangle arc = new Rectangle(rectangle.Location, size);

                // 根据指定的渐变角度计算起点和终点坐标
                Point startPoint = new Point();
                Point endPoint = new Point();
                CalculateGradientPoints(rectangle, gradientAngle, ref startPoint, ref endPoint);

                // 创建渐变画刷
                LinearGradientBrush brush = new LinearGradientBrush(startPoint, endPoint, startColor, endColor);

                // 左上角
                GraphicsPath path = CreateRoundedRectangle(rectangle, cornerRadius);

                // 填充圆角四边形
                graphics.FillPath(brush, path);

                // 绘制圆角四边形边线
                if (needpath)
                {
                    graphics.DrawPath(pen, path);
                }
            }catch (Exception ex)
            {

            }
            
        }
        public static GraphicsPath CreateRoundedRectangle(Rectangle rect, int cornerRadius)
        {
            GraphicsPath path = new GraphicsPath();
            int radius = cornerRadius * 2;

            // 左上角
            path.AddArc(rect.Left, rect.Top, radius, radius, 180, 90);
            path.AddLine(rect.Left + cornerRadius, rect.Top, rect.Right - cornerRadius, rect.Top);

            // 右上角
            path.AddArc(rect.Right - radius, rect.Top, radius, radius, 270, 90);
            path.AddLine(rect.Right, rect.Top + cornerRadius, rect.Right, rect.Bottom - cornerRadius);

            // 右下角
            path.AddArc(rect.Right - radius, rect.Bottom - radius, radius, radius, 0, 90);
            path.AddLine(rect.Right - cornerRadius, rect.Bottom, rect.Left + cornerRadius, rect.Bottom);

            // 左下角
            path.AddArc(rect.Left, rect.Bottom - radius, radius, radius, 90, 90);
            path.AddLine(rect.Left, rect.Bottom - cornerRadius, rect.Left, rect.Top + cornerRadius);
            
            path.CloseFigure();
            return path;
        }
        public static void DrawRoundedRectangle(Graphics graphics, Pen pen, Brush fillBrush, Rectangle rectangle, int cornerRadius)
        {
            try
            {
                int diameter = cornerRadius * 2;
                Size size = new Size(diameter, diameter);
                // 左上角
                GraphicsPath path = CreateRoundedRectangle(rectangle, cornerRadius);
                // 填充圆角四边形
                graphics.FillPath(fillBrush, path);
                // 绘制圆角四边形边线
                graphics.DrawPath(pen, path);
            }catch (Exception ex)
            {

            }
            
        }



        public class PopWindow
        {
            public string Title { get; set; }
            public string Content { get; set; }
            public Form form;
            private System.Windows.Forms.Label label;
            private bool UseBar = true;
            private float minValue = 0;
            private float maxValue = 100;
            private float value = 0;
            private PictureBox _plugImage;
            private bool IsHide = false;
            public void Close()
            {
                form.Invoke((Action)(() =>
                {
                    IsHide = true;
                    form.Hide();
                }));

            }
            public PopWindow(string title, string content, System.Drawing.Image icon = null)
            {
                form = new Form();
                form.Text = title;
                form.Size = new Size(formWidth, formHeight);
                form.StartPosition = FormStartPosition.Manual;
                form.FormBorderStyle = FormBorderStyle.FixedSingle;
                form.ControlBox = false;
                form.MaximizeBox = false; form.MinimizeBox = false;
                form.ShowIcon = false;
                form.ShowInTaskbar = false;
                form.TopMost = true;
                if (icon != null)
                {
                    form.Icon = Icon.FromHandle(((Bitmap)icon).GetHicon());
                    form.ShowIcon = true;
                }
                Title = title;
                Content = content;
                WindowList.Insert(0, this);
                //添加显示对象
                label = new System.Windows.Forms.Label();
                label.Location = new Point(0, 0);
                label.BackColor = Color.Transparent;
                label.Width = form.ClientSize.Width;
                label.Height = form.ClientSize.Height;
                label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                label.Text = content;
                label.Click += Form_Click;
                form.Controls.Add(label);
                form.FormClosed += Form_FormClosed;
                form.Shown += Form_Shown;
                form.Paint += OnPaint;
                form.Click += Form_Click;
                if (icon != null)
                {
                    PictureBox plugImage = new System.Windows.Forms.PictureBox();
                    plugImage.Image = icon;
                    plugImage.Width = 30;
                    plugImage.Height = 30;
                    plugImage.Location = new Point(10, 10);
                    plugImage.SizeMode = PictureBoxSizeMode.Zoom;
                    plugImage.Click += Form_Click;
                    _plugImage = plugImage;
                    form.Controls.Add(plugImage);
                    label.Location = new Point(50, 0);
                    label.Width = form.ClientSize.Width - 50;
                }
                ReSizeLabel();
                form.Show();
            }

            private void Form_Click(object sender, EventArgs e)
            {
                main.ShowPrintLog(Title);
            }
            private void ReSizeLabel()
            {
                if (UseBar)
                {
                    label.Height = form.ClientSize.Height - 30;
                }
                else
                {
                    label.Width = form.ClientSize.Width;
                    label.Height = form.ClientSize.Height;
                }
            }
            public void DisableProgressBar()
            {
                UseBar = false;
                form.Invalidate();
            }
            public void SetIcon(System.Drawing.Image data)
            {
                form.Invoke((Action)(() =>
                {
                    form.Icon = Icon.FromHandle(((Bitmap)data).GetHicon());
                    form.ShowIcon = true;
                    form.Invalidate();
                    if (_plugImage != null)
                    {
                        _plugImage.Image = data;
                    }
                }));
            }
            public float GetMax()
            {
                return maxValue;
            }
            public float GetValue()
            {
                return value;
            }
            public void AddMax(float max)
            {
                maxValue += max;
                form.Invalidate();
            }
            public void SetMax(float max)
            {
                maxValue = max;
                form.Invalidate();
            }
            public void SetMin(float min)
            {
                minValue = min;
                form.Invalidate();
            }
            public void SetMsg(string msg)
            {
                label.Invoke((Action)(() =>
                {
                    label.Text = msg;
                    if (IsHide)
                    {
                        IsHide = false;
                        form.Show();
                    }
                }));
            }
            public void AddValue(float thisvalue)
            {
                value += thisvalue;
                if (value < minValue)
                {
                    minValue = thisvalue;
                }
                if (value > maxValue)
                {
                    maxValue = thisvalue;
                }
                form.Invalidate();
            }
            public void SetValue(float thisvalue)
            {
                if (value < minValue)
                {
                    minValue = thisvalue;
                }
                if (value > maxValue)
                {
                    maxValue = thisvalue;
                }
                value = thisvalue;
                form.Invalidate();
            }
            public void EnableProgressBar(float minvalue, float maxvalue)
            {
                minValue = minvalue;
                maxValue = maxvalue;
                UseBar = true;
                form.Invalidate();
            }
            public float ProgressValue
            {
                get
                {
                    if (value < minValue)
                    {
                        value = minValue;
                    }
                    else if (value > maxValue)
                    {
                        value = maxValue;
                    }
                    // 计算百分比
                    float range = maxValue - minValue;
                    float progress = value - minValue;
                    float percentage = progress / range;

                    return percentage;
                }
            }
            private void OnPaint(object sender, PaintEventArgs e)
            {
                Console.WriteLine(form.Height);
                Rectangle rect = new Rectangle(10, form.ClientSize.Height - 30, form.ClientSize.Width - 20, 20);
                Pen pen = new Pen(Color.FromArgb(0x50, 0x0, 0x0, 0x0), 1);
                Pen pen1 = new Pen(Color.FromArgb(0x50, 0xFF, 0xFF, 0xFF), 1);
                SolidBrush solidBrush = new SolidBrush(Color.FromArgb(0x9c, 0xa0, 0xdf, 0xff));
                var g = e.Graphics;
                g.SmoothingMode = SmoothingMode.HighQuality;
                // 在窗体上绘制路径
                DrawRoundedRectangle(g, pen, solidBrush, rect, 8);
                //绘制进度
                Rectangle rect1 = new Rectangle(12, form.ClientSize.Height - 28, IntProgressValue(form.ClientSize.Width - 24), 16);
                DrawGradientRoundedRectangle(g, pen1, Color.FromArgb(0xFF, 0x22, 0x6C, 0xC5), Color.FromArgb(0xFF, 0x6C, 0xD9, 0x75), rect1, 6, 0.75f, true);
                //绘制当前数字
                FontStyle fontStyle = FontStyle.Bold;
                Font font = new Font("Arial", 30, fontStyle);

                string text = value.ToString();
                SizeF textSize = g.MeasureString(text, font);

                // 设置绘制文字的位置
                float x = ((form.ClientSize.Width - 20) - textSize.Width) / 2+10;
                float y = (20 - textSize.Height) / 2+ form.ClientSize.Height - 30;

                GraphicsPath path = new GraphicsPath();
                path.AddString(text, font.FontFamily, (int)fontStyle, font.Size, new Point((int)x, (int)y), StringFormat.GenericDefault);
                Pen penb = new Pen(Color.White, 4);
                g.DrawPath(penb, path);
                // 填充文字
                g.FillPath(Brushes.Red, path);
            }
            private int IntProgressValue(int width)
            {
                return (int)(width * ProgressValue);
            }
            public void SetTitle(string title)
            {
                form.Text = title;
            }
            public void SetContent(string content)
            {

            }
            private void Form_Shown(object sender, EventArgs e)
            {
                ArrangeWindows();
            }

            private void Form_FormClosed(object sender, FormClosedEventArgs e)
            {
                WindowList.Remove(this);
                ArrangeWindows();
            }
        }
    }
}